<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Category;
use App\Model\Content;
use App\Model\Like;
use Illuminate\Support\Facades\DB;

class ContentController extends Controller
{
  // 获取文章列表
  public function getContentList()
  {
    $data = Content::orderBy('status', 'asc')->orderBy('id', 'asc')->limit(4)->get();
    foreach ($data as $value) {
      // 遍历添加联表得到的对应分类名称
      $value['catename'] = $value->category->name;
    }
    return response()->json($data);
  }

  // 根据分类id获取文章列表
  public function getContentByCid($cid)
  {
    $data = Content::where('cid', $cid)->limit(4)->get();
    foreach ($data as $value) {
      $value['count'] = $value->comments->count();
    }
    $name = Category::find($cid)->name;
    return response()->json([
      'body' => $data,
      'name' => $name
    ]);
  }

  // 获取热门内容
  public function getHotContent()
  {
    $hotData = [];
    $hotContent =
      Like::select('cid', DB::raw('count(*) as num'))
      ->orderBy('num', 'desc')
      ->groupBy('cid')
      ->limit(2)
      ->get();
    foreach ($hotContent as $value) {
      $hotData[] = $value->content;
    }
    return response()->json($hotData);
  }
}
